package model

import (
	"time"
	"tools-api/src/common/db/database"
	"tools-api/src/common/utils"
)

type User struct {
	Id         int64     `json:"-"`
	JId        string    `json:"id"`
	Uuid       string    `json:"uuid"`
	Phone      string    `json:"phone"`
	Password   string    `json:"-"`
	MfaSecret  string    `json:"-"`           // MFA密钥
	MfaEnabled int       `json:"mfa_enabled"` // MFA是否开启
	CreatedAt  time.Time `xorm:"created" json:"-"`
	ModifiedAt time.Time `xorm:"updated" json:"-"`
	DeleteMark int       `xorm:"delete_mark" json:"-"`
}

func (User) Create(phone, password string) error {
	user := User{
		Phone:    utils.Encrypt(phone),
		Password: utils.Md5String(password),
	}
	_, err := database.JCJEngine.Insert(&user)
	return err
}

// Verify 校验密码
func (user User) Verify(phone, password string) User {
	_, _ = database.JCJEngine.
		Where("phone=? and password=?", utils.Encrypt(phone), utils.Md5String(password)).
		Get(&user)
	return user
}

// GetUserByUuid 根据uuid获取用户
func (user User) GetUserByUuid(uuid string) User {
	_, _ = database.JCJEngine.Where("uuid=?", uuid).Get(&user)
	return user
}

// EnableMfa 修改mfa开关
func (user User) EnableMfa(uuid string, enabled bool) error {
	if enabled {
		user.MfaEnabled = 1
	} else {
		user.MfaEnabled = 0
	}
	_, err := database.JCJEngine.Where("uuid=?", uuid).Cols("mfa_enabled").Update(&user)
	return err
}
